/*
    Nios-sim - one simple NIOSII simulator only for personal interest and fun.
    Copyright (C) 2010  chysun2000@gmail.com

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "public.h"
#include "niosii.h"
#include "io_device.h"
#include "nor_flash.h"

static struct nor_flash_core_hw hw;

static void flash_init(struct io_device * self)
{
	memset(&hw, 0x00, sizeof(struct nor_flash_core_hw));
	self->priv_data = &hw;
	
	hw.phys_base_addr = NOR_FLASH_BASE_ADDR;
	hw.size = NOR_FLASH_SIZE;
	hw.status = STATUS_READ;
	hw.mem_base_addr = (unsigned char *)malloc(hw.size);
	
	printf("NOR Flash Module: PHYS:0x%08X at %p size:0x%08X\n",
			hw.phys_base_addr, hw.mem_base_addr, hw.size);
}

static int32_t flash_is_belong(uint32_t address)
{
	int32_t ret_val = ADDR_IS_NOT_DEV;
	
	if (address >= hw.phys_base_addr && address <(hw.phys_base_addr + hw.size)){
		ret_val = ADDR_IS_DEV;
	}
	return ret_val;
}

/* only support 8bit access */
static uint32_t flash_read(struct io_device * self, uint32_t addr, uint32_t data_len)
{
	uint32_t ret_val = 0;
	uint8_t * data = (uint8_t *)hw.mem_base_addr;
	
	if(data_len == (hw.bus_width / 8)){
		ret_val = (uint32_t)(data[addr - hw.phys_base_addr]);
		printf("%s->%x:%x\n",__func__,addr,ret_val);
	}
	return ret_val;
}

static int32_t judge_special_addr(uint32_t addr)
{
	int32_t ret_val = SIM_TRUE;
	return ret_val;
}

static void handle_special_operation(uint32_t addr, uint32_t data)
{
	
}

static void flash_write(struct io_device * self, uint32_t addr, uint32_t data, 
						uint32_t data_len)
{
	uint8_t * data_buf = (uint8_t *)hw.mem_base_addr;
	
	/* judge whether the address is the special address */
	if (judge_special_addr(addr) == SIM_TRUE){
		handle_special_operation(addr, data);
	} else {
		if (hw.status == STATUS_CHIP_ERASE || hw.status == STATUS_SECTION_ERASE){
			if (data_len == (hw.bus_width/8)){
				data_buf[(addr - hw.phys_base_addr)] = (uint8_t)(data & 0xFF);
			}
		}
	}
}

struct io_device nor_flash_core = {
	.name = "NOR Flash Core",
	.init = flash_init,
	.is_belong = flash_is_belong,
	.read_data = flash_read,
	.write_data = flash_write,
	.has_irq = NULL,
	.simulate = NULL,
	.irq_enable_mask = 0,
};

uint8_t * nor_flash_mem_addr(void)
{
	return hw.mem_base_addr;
}


